﻿Imports System.IO
Imports System.Data.SqlClient
Public Class FormLogin

    Public mor, mout, afin, afout, perId, sysoff, ecode, timeoff, timeRelax As String
    Dim BackgroundID As Int16
    Dim tooltip As New ToolTip

    Public Function IsAuthorized(ByVal permissionId As Int16) As Boolean

        Dim c = Cmd.ExecuteScalar("SELECT COUNT(*) FROM SYS_ROLE_PERMISSION WHERE ROLE_ID=" & perId & " AND PERMISSION_ID=" & permissionId)
        If c > 0 Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        loadBackground()

        Me.WindowState = FormWindowState.Maximized
        Me.Panel1.Location = New System.Drawing.Point(488, 190)

        Try

            swithSystem()

            DisplyTime()
            If Now.ToShortTimeString > CDate(mout) And CDate(Now.ToShortTimeString) < CDate(afin) Then
                Label7.Text = "This is relax time(admin only)"
                Label6.Hide()

            ElseIf Now.ToShortTimeString > CDate(timeRelax) Then
                Label7.Text = "Welcome for Afternoon login"
                Label6.Text = "I can't access this account"
            Else
                Label7.Text = "Welcome for Morning login"
                Label6.Text = "I can't access this account"

            End If

        Catch ex As Exception

        End Try

    End Sub

    Public Sub DisplyTime()
        Try

            Dim dt = Cmd.ExecuteDataTable("SELECT * FROM TBL_DEFUALT_TIME ")

            If (dt.Rows.Count = 1) Then

                Me.timeRelax = dt(0)("BREAK_TIME")

                Me.afin = dt(0)("AFTERNOON_IN")

                Me.afout = dt(0)("AFTERNOON_OUT")


                Me.mor = dt.Rows(0)("MORNING_IN")

                Me.mout = dt.Rows(0)("MORNING_OUT")

            End If

        Catch ex As Exception
            LblNocn.Text = "Sorry, no connection to databases server"
        End Try
    End Sub

    Public Sub RelaxTime()
        Try


            If Now.ToShortTimeString > CDate(mout) And CDate(Now.ToShortTimeString) < CDate(afin) Then
                Dim LoginMor = Cmd.ExecuteDataTable("SELECT * FROM SYS_USER WHERE USER_NAME='" & txtUserName.Text & "' AND PASSWORD='" & Txtpassword.Text & "'")
                If (LoginMor.Rows.Count = 1) Then

                    Me.perId = LoginMor.Rows(0)("ROLE_ID")
                    Me.ecode = LoginMor.Rows(0)("USER_CODE")
                Else
                    tooltip.IsBalloon = True
                    Me.Highlighter1.SetHighlightColor(Me.Txtpassword, DevComponents.DotNetBar.Validator.eHighlightColor.Red)
                    Me.Highlighter1.SetHighlightColor(Me.txtUserName, DevComponents.DotNetBar.Validator.eHighlightColor.Red)
                    tooltip.InitialDelay = 10
                    tooltip.ToolTipTitle = "Error User name or Password"
                    tooltip.ToolTipIcon = ToolTipIcon.Error
                    tooltip.SetToolTip(Txtpassword, "You maybe login with incorrect password or user name!")
                    tooltip.SetToolTip(txtUserName, "You maybe login with incorrect password or user name!")
                    Txtpassword.Clear()
                    txtUserName.Focus()
                    txtUserName.SelectAll()
                    Exit Sub
                End If
                tooltip.IsBalloon = True
                Me.Highlighter1.SetHighlightColor(Me.Txtpassword, DevComponents.DotNetBar.Validator.eHighlightColor.Green)
                Me.Highlighter1.SetHighlightColor(Me.txtUserName, DevComponents.DotNetBar.Validator.eHighlightColor.Green)
                tooltip.InitialDelay = 10
                tooltip.ToolTipTitle = "Error User name or Password"
                tooltip.ToolTipIcon = ToolTipIcon.Error
                tooltip.SetToolTip(Txtpassword, "For Administrator only!")
                tooltip.SetToolTip(txtUserName, "For Administrator only!")
                Txtpassword.Clear()
                txtUserName.Focus()
                txtUserName.SelectAll()
                '===========
                If perId = IsAuthorized(1) Then
                    Me.Hide()

                    FormMain.DataGridLoadData.ContextMenuStrip = Nothing
                    FormMain.DataGridLoadData.DataSource = Cmd.ExecuteDataTable("Select * from TBL_TIME_WORK")

                    FormMain.FormatDataGridViews()
                    countsmsuser()
                    FormMain.ShowDialog()

                    Exit Sub
                Else



                    Exit Sub
                    loadDdata()
                End If
                '====================================
            Else
                Label7.Text = "Welcome for Afternoon login"
                Label6.Show()
                Label6.Text = "I can't access this account"
                LBL_Login.Enabled = False
                LBL_Login.Enabled = False

            End If
        Catch ex As Exception
            '   MsgBox(ex.Message)
        End Try
    End Sub



    Public Sub Login()
        FormMain.LBL_NAME.Text = txtUserName.Text
        Try


            'General Login
            Dim LogOutAfter = Cmd.ExecuteDataTable("SELECT * FROM SYS_USER WHERE USER_NAME='" & txtUserName.Text & "' AND PASSWORD='" & Txtpassword.Text & "' AND ACTIVE=1")
            If (LogOutAfter.Rows.Count = 1) Then

                Me.perId = LogOutAfter.Rows(0)("ROLE_ID")
                Me.ecode = LogOutAfter.Rows(0)("USER_CODE")
            Else
                tooltip.IsBalloon = True
                Me.Highlighter1.SetHighlightColor(Me.Txtpassword, DevComponents.DotNetBar.Validator.eHighlightColor.Red)
                Me.Highlighter1.SetHighlightColor(Me.txtUserName, DevComponents.DotNetBar.Validator.eHighlightColor.Red)
                tooltip.InitialDelay = 10
                tooltip.ToolTipTitle = "Error User name or Password"
                tooltip.ToolTipIcon = ToolTipIcon.Error
                tooltip.SetToolTip(Txtpassword, "You maybe login with incorrect password or user name!")
                tooltip.SetToolTip(txtUserName, "You maybe login with incorrect password or user name!")
                Txtpassword.Clear()
                txtUserName.Focus()
                txtUserName.SelectAll()

                Exit Sub
            End If
            '======================================
            'For Admin Login
            If perId = IsAuthorized(1) Then

                Me.Hide()
                With FormMain
                    .TabEmployee.Visible = True
                    .TabReport.Visible = True
                    .TabHolidays.Visible = True
                    .TabSetting.Visible = True
                    .TabPermission.Visible = True
                    .TabSystemRequire.Visible = True
                    .TabAttendance.Visible = True

                    .LBL_Employee.Visible = True
                    .LBL_Attendance.Visible = True
                    .LBL_Report.Visible = True
                    .lBL_Holiday.Visible = True
                    .LBL_Setting.Visible = True
                    .LBL_Permission.Visible = True
                    .LBL_RestoreDatabase.Visible = True
                    .LBL_UserRequest.Location = New System.Drawing.Point(0, 223)
                    .LBL_LogOut.Location = New System.Drawing.Point(-1, 335)
                    .LBL_About.Location = New System.Drawing.Point(3, 372)
                    '=======================
                    .BtnChekIn.Hide()
                    .BtnChekOut.Hide()
                    'loadUserRequest()
                    .txtUserCode.ReadOnly = False
                    .txtUserCode.Text = ""
                    .txtUserName.Text = ""
                    .txtUserphone.Text = ""
                    .txtDescription.Text = ""
                    .txtcode.Focus()
                    .lblMessage.Show()
                    countsmsuser()
                    loadDataUserRequest()
                    ToolRequestOptionForAdmin()
                    .DataGridLoadData.DataSource = Cmd.ExecuteDataTable("SELECT * FROM TBL_TIME_WORK ORDER BY [DATE] DESC ")
                    .Label22.Text = .DataGridLoadData.RowCount.ToString() & " Record(s)"
                    ActiveTimeWorkColorForAdmin()
                    'Dim frm As New FormMain
                    .FormatDataGridViews()
                    Me.holiday()
                    Me.loadImage()
                    .ecode = ecode
                    .Show()
                    '==============================
                    .DgvUserLogin.ReadOnly = False
                    For Each column As DataGridViewColumn In .DgvUserLogin.Columns
                        column.ReadOnly = True
                    Next
                    .DgvUserLogin.Columns("PASSWORD").ReadOnly = False

                    .Dgvholiday.ReadOnly = False
                    .Dgvholiday.MultiSelect = True
                    '==============================
                End With

                Exit Sub
            Else

                loadDdata()

            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub
    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
        FormProgressBarLoad.Close()


    End Sub

    Private Sub Label1_MouseHover(sender As Object, e As EventArgs) Handles Label1.MouseHover
        Label1.ForeColor = Color.White
        Label1.BackColor = Color.Red
    End Sub

    Private Sub Label1_MouseLeave(sender As Object, e As EventArgs) Handles Label1.MouseLeave
        Label1.ForeColor = Color.Black
        Label1.BackColor = Color.Transparent
    End Sub


    Private Sub Label6_MouseHover(sender As Object, e As EventArgs) Handles Label6.MouseHover

        Label6.ForeColor = Color.Yellow

    End Sub

    Private Sub Label6_MouseLeave(sender As Object, e As EventArgs) Handles Label6.MouseLeave

        Label6.ForeColor = Color.White
    End Sub

    Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint
        Timer1_Tick(sender, e)

    End Sub

    Public Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        timeoff = Now.ToLongTimeString
        lbltime.Text = Now.ToLongTimeString
        Timer1.Enabled = True
        Timer1.Interval = 1000
        If timeoff = sysoff Then
            autoAttendace()
            Me.Close()
        End If


    End Sub

    Public Sub swithSystem()
        Try

            Dim loginMor = Cmd.ExecuteDataTable("SELECT * FROM TBL_SWITH_SYSTEM")
            If (loginMor.Rows.Count = 1) Then

                Me.sysoff = loginMor.Rows(0)("SwithSystem")
            End If

        Catch ex As Exception

        End Try

    End Sub
    Public Sub autoAttendace()
        Try
            Cmd.ExecuteNonquery("INSERT INTO TBL_ATTENDENT (EMP_ID,EMP_CODE,EMP_NAME,ABSENT_DATE,ACTIVE) SELECT E.EMP_ID,E.EMP_CODE,E.EMP_NAME,GETDATE(),E.ACTIVE FROM TBL_EMPLOYEE E LEFT JOIN TBL_STORE_EMPLOYEE A ON E.EMP_ID = A.EMP_ID WHERE A.ABSENT_DATE <>'DE' and A.ACTIVE<>0 ")
            Cmd.ExecuteNonquery("UPDATE TBL_STORE_EMPLOYEE SET ACTIVE=1 WHERE ABSENT_DATE<>'DE'")
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub
    Public Sub off()
        Try


            If Now.ToShortTimeString > (sysoff) Then
                Me.Close()
            End If
        Catch ex As Exception

            ' MsgBox(ex.Message)
        End Try
    End Sub




    Public Sub loadDdata()
        Try

            Me.Hide()

            With FormMain


                .DataGridLoadData.DataSource = Cmd.ExecuteDataTable("SELECT * FROM TBL_TIME_WORK WHERE EMP_CODE='" & ecode & "'ORDER BY [DATE] DESC ")
                .Label22.Text = .DataGridLoadData.RowCount.ToString() & " Record(s)"


                .TabEmployee.Visible = False
                .TabReport.Visible = False
                .TabHolidays.Visible = False
                .TabSetting.Visible = False

                .TabSystemRequire.Visible = False
                .TabAttendance.Visible = False
                .TabPermission.Visible = False
                .LBL_Employee.Visible = False
                .LBL_Attendance.Visible = False
                .LBL_Report.Visible = False
                .lBL_Holiday.Visible = False
                .LBL_Setting.Visible = False
                .LBL_Permission.Visible = False
                .LBL_RestoreDatabase.Visible = False
                .txtUserCode.ReadOnly = True
                loadUserRequest()
                userrequestoption()
                ToolRequestOptionGeneralUser()
                '--------------------------------------------------------------
                .LBL_UserRequest.Location = New System.Drawing.Point(1, 38)
                .LBL_LogOut.Location = New System.Drawing.Point(0, 76)
                .LBL_About.Location = New System.Drawing.Point(0, 113)

                .FormatDataGridViews()
                Me.holiday()
                Me.loadImage()
                .ecode = ecode
                .Show()

            End With
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub
    Public Sub loadImage()


        Dim picLoad = Cmd.ExecuteDataTable("SELECT  PHOTO FROM TBL_EMPLOYEE WHERE EMP_CODE='" & ecode & "'")

        If picLoad.Rows.Count > 0 And Convert.ToString(picLoad.Rows(0)("PHOTO")) = "" Then
            FormMain.PicProfile.Image = Nothing
            '    MsgBox("No picture load")
            Exit Sub

        End If
        Try
            Dim sql As String = "Select  PHOTO from TBL_EMPLOYEE where EMP_CODE='" + ecode + "'"

            Dim cmd1 As New SqlCommand(sql, Cmd.GetConnection)
            Dim reader As SqlDataReader = cmd1.ExecuteReader()
            reader.Read()
            If reader.HasRows Then

                Dim img As Byte() = DirectCast(reader(0), Byte())
                If img Is Nothing Then
                    FormMain.PicProfile.Image = Nothing
                Else
                    Dim ms As New MemoryStream(img)
                    FormMain.PicProfile.Image = Image.FromStream(ms)


                End If
            Else
                'MessageBox.Show("This is does not exist. ")



            End If
        Catch ex As Exception


        End Try
    End Sub


    Private Sub LBL_Login_Click(sender As Object, e As EventArgs) Handles LBL_Login.Click
        Try



            If Now.ToShortTimeString > CDate(mout) And CDate(Now.ToShortTimeString) < CDate(afin) Then
                RelaxTime()
            Else

                Login()

            End If
        Catch ex As Exception
            '  MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Txtpassword_KeyDown(sender As Object, e As KeyEventArgs) Handles Txtpassword.KeyDown
        Try


            If e.KeyCode = Keys.Enter And LBL_Login.Enabled = True Then
                LBL_Login_Click(sender, e)

            End If
        Catch ex As Exception
            ' MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
        Dim frm As New FormUserRequest
        frm.ShowDialog()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)

    End Sub



    Public Sub generalDataUserRequest()
        'Select data from TBL_USER_REQUEST WHERE ACTIVE=1 for general user

        Try
            With FormMain


                .DgvUserRequest.DataSource = Cmd.ExecuteDataTable("SELECT * FROM TBL_USER_REQUEST WHERE REQUEST_NAME='" & .LBL_NAME.Text & "' AND ACTIVE=1")
                .Label16.Text = .DgvUserRequest.RowCount.ToString() & " Records"
                userrequestoption()
            End With
        Catch ex As Exception

        End Try
    End Sub
    Public Sub loadUserRequest() 'general user
        FormMain.DgvUserRequest.DataSource = Cmd.ExecuteDataTable("SELECT  * FROM TBL_USER_REQUEST WHERE REQUEST_NAME='" & txtUserName.Text & "' AND ACTIVE=1")
        FormMain.Label16.Text = FormMain.DgvUserRequest.RowCount.ToString() & " Records"
        FormMain.lblMessage.Hide()
    End Sub

    Public Sub countsmsuser() 'for admin
        FormMain.lblMessage.Text = Cmd.ExecuteScalar("SELECT COUNT (*) FROM TBL_USER_REQUEST WHERE ACTIVE=1")
    End Sub
    Public Sub loadDataUserRequest()
        'Select data from TBL_USER_REQUEST WHERE ACTIVE=1 for admin

        Try

            FormMain.DgvUserRequest.DataSource = Cmd.ExecuteDataTable("SELECT * FROM TBL_USER_REQUEST WHERE ACTIVE=1 ")
            FormMain.Label16.Text = FormMain.DgvUserRequest.RowCount.ToString() & " Record(s)"
            '  userrequestoption()
        Catch ex As Exception

        End Try
    End Sub
    Public Sub userrequestoption()
        With FormMain
            .txtUserCode.Text = ecode
            .txtUserName.Text = txtUserName.Text
            .txtUserphone.Text = Cmd.ExecuteScalar("SELECT PHONE FROM TBL_EMPLOYEE WHERE EMP_NAME='" & txtUserName.Text & "'")

        End With
    End Sub

    Private Sub ShowPasswordToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ShowPasswordToolStripMenuItem.Click
        Txtpassword.PasswordChar = ""
    End Sub

    Private Sub HidePasswordToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles HidePasswordToolStripMenuItem.Click
        Txtpassword.PasswordChar = "*"

    End Sub




    Public Sub loadBackground()
        Try



            BackgroundID = Cmd.ExecuteScalar("SELECT BACKGROUND_CODE FROM TBL_BACKGROUND WHERE BACKGROUND_ID=1")
            If BackgroundID = 1 Then
                Me.Txtpassword.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile
                Me.BackgroundImage = Global.TimeManagementSystem.My.Resources.Resources.Background

                Me.PictureBox1.Hide()
                Exit Sub
            End If
            If BackgroundID = 3 Then
                Me.BackColor = Color.White
                Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile

                Me.BackgroundImage = Global.TimeManagementSystem.My.Resources.Resources.bg1

                Me.PictureBox1.Hide()

                Exit Sub
            End If
            '=================================
            If BackgroundID = 4 Then
                Me.BackColor = Color.White
                Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile

                Me.BackgroundImage = Global.TimeManagementSystem.My.Resources.Resources.AbstractBlue

                Me.PictureBox1.Hide()

                Exit Sub
            End If

            '================================
            If BackgroundID = 5 Then
                Me.BackColor = Color.White
                Me.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Tile

                Me.BackgroundImage = Global.TimeManagementSystem.My.Resources.Resources.bg3

                Me.PictureBox1.Hide()

                Exit Sub
            End If
            '================================
            If BackgroundID = 2 Then
                Me.BackColor = Color.Black
                PictureBox1.Show()
                Exit Sub
            End If
        Catch ex As Exception
            ' MsgBox(ex.Message)
        End Try
    End Sub
    Public Sub holiday()
        With FormMain



          


            Dim holidaydate = Cmd.ExecuteScalar("SELECT  DESCRIPTION FROM TBL_HOLIDAY WHERE DATE ='" & Now.ToShortDateString & "' AND ACTIVE=1")

         

            .Label15.ForeColor = Color.Red
            .Label15.Text = "Today is " + holidaydate
            If .Label15.Text = "Today is " Then

                .BtnChekIn.Show()
                .BtnChekOut.Show()
                .Label15.Hide()
            Else
                .BtnChekOut.Hide()
                .BtnChekIn.Hide()
                .Label15.Show()

            End If

            If perId = 1 And .Label15.Text = "Today is " Then
                .BtnChekOut.Hide()
                .BtnChekIn.Hide()

                Exit Sub
            ElseIf perId = 1 And .Label15.Text <> "Today is " Then
                .Label15.Show()
            End If

        End With
        
    End Sub
    Public Sub ToolRequestOptionGeneralUser()
        With FormMain
            .ToolRestoreDB.Enabled = False
            .ToolCancel.Enabled = False
            .ToolDelete.Enabled = False
            .ToolViewDeletedDocument.Enabled = False
            '.ToolClose.Enabled = False
            .ToolRefresh.Enabled = False
            .ToolUpdate.Enabled = False
        End With
    End Sub
    Public Sub ToolRequestOptionForAdmin()
      
        With FormMain
            .ToolRestoreDB.Enabled = True
            .ToolCancel.Enabled = True
            .ToolDelete.Enabled = True
            .ToolViewDeletedDocument.Enabled = True

            .ToolRefresh.Enabled = True
            .ToolUpdate.Enabled = True
        End With
    End Sub
    Public Sub ActiveTimeWorkColorForAdmin()
        For Each row As DataGridViewRow In FormMain.DataGridLoadData.Rows
            If row.Cells("DATETIME").Value = Now.ToShortDateString Then

                row.Cells("DATETIME").Style.ForeColor = Color.Blue
                row.Cells("EMP_CODE").Style.ForeColor = Color.Blue
                row.Cells("EMP_NAME").Style.ForeColor = Color.Blue

                row.Cells("MORNING_IN").Style.ForeColor = Color.Blue
                row.Cells("MORNING_OUT").Style.ForeColor = Color.Blue
                row.Cells("Total").Style.ForeColor = Color.Blue

                row.Cells("AFTERNOON_IN").Style.ForeColor = Color.Blue
                row.Cells("AFTERNOON_OUT").Style.ForeColor = Color.Blue
                row.Cells("ATotal").Style.ForeColor = Color.Blue

            End If

            'row.Cells("ABSENT_DATE").Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        Next
    End Sub
End Class